<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form" style="padding: -10px">
			<el-form ref="formRef" :model="stateData.vmModel" label-width="100px">
				<el-row :gutter="20">
					<el-col :xs="24" :lg="24" class="mb20">
						<el-form-item ref="Entity_Title_FormItem" prop="Entity.Title" :rules="[{ required: true, message: '文章标题为必填项', trigger: 'blur' }]">
							<template #label>
								<WtmLabelTooltip label="文章标题" tooltip="文章标题" />
							</template>
							<el-input v-model="stateData.vmModel.Entity.Title" clearable></el-input>
						</el-form-item>
					</el-col>
					<!-- <el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_SubTitle_FormItem" prop="Entity.SubTitle">
								<template #label>
									<WtmLabelTooltip label="副标题" tooltip="文章副标题" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.SubTitle" clearable></el-input>
							</el-form-item>
						</el-col> -->
					<el-col :xs="24" :lg="24" class="mb20">
						<el-form-item ref="Entity_Summary_FormItem" prop="Entity.Summary">
							<template #label>
								<WtmLabelTooltip label="文章摘要" tooltip="文章摘要或简介" />
							</template>
							<el-input type="textarea" v-model="stateData.vmModel.Entity.Summary" clearable :rows="4"></el-input>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :lg="6" class="mb20">
						<el-form-item ref="Entity_CategoryId_FormItem" prop="Entity.CategoryId">
							<template #label>
								<WtmLabelTooltip label="文章分类" tooltip="关联的文章分类" />
							</template>
							<el-select v-model="stateData.vmModel.Entity.CategoryId" clearable>
								<el-option v-for="item in stateData.AllSysArticleCategorys" :key="item.Value" :value="item.Value" :label="item.Text"></el-option
							></el-select>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :lg="6" class="mb20">
						<el-form-item ref="Entity_Status_FormItem" prop="Entity.Status">
							<template #label>
								<WtmLabelTooltip label="文章状态" tooltip="文章状态" />
							</template>
							<el-select v-model="stateData.vmModel.Entity.Status" clearable>
								<el-option key="草稿" value="草稿" label="草稿"></el-option>
								<el-option key="已发布" value="已发布" label="已发布"></el-option>
								<el-option key="已下线" value="已下线" label="已下线"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :lg="6" class="mb20">
						<el-form-item ref="Entity_IsTop_FormItem" prop="Entity.IsTop" :rules="[{ required: true, message: '是否置顶为必填项', trigger: 'blur' }]">
							<template #label>
								<WtmLabelTooltip label="是否置顶" tooltip="是否置顶显示" />
							</template>
							<el-select v-model="stateData.vmModel.Entity.IsTop" clearable>
								<el-option :key="1" :value="true" :label="$t('message._system.common.vm.tips_bool_true')"></el-option>
								<el-option :key="0" :value="false" :label="$t('message._system.common.vm.tips_bool_false')"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :lg="6" class="mb20">
						<el-form-item
							ref="Entity_IsRecommend_FormItem"
							prop="Entity.IsRecommend"
							:rules="[{ required: true, message: '是否推荐为必填项', trigger: 'blur' }]"
						>
							<template #label>
								<WtmLabelTooltip label="是否推荐" tooltip="是否推荐文章" />
							</template>
							<el-select v-model="stateData.vmModel.Entity.IsRecommend" clearable>
								<el-option :key="1" :value="true" :label="$t('message._system.common.vm.tips_bool_true')"></el-option>
								<el-option :key="0" :value="false" :label="$t('message._system.common.vm.tips_bool_false')"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="20">
					<el-col :xs="24" :lg="24" class="mb20">
						<el-form-item
							ref="Entity_Content_FormItem"
							prop="Entity.Content"
							:rules="[{ required: true, message: '文章内容为必填项', trigger: 'blur' }]"
						>
							<template #label>
								<WtmLabelTooltip label="文章内容" tooltip="文章正文内容" />
							</template>
							<wtm-md-editor
								v-model="stateData.vmModel.Entity.Content"
								height="700px"
								:pdf-file-name="`${stateData.vmModel.Entity.Title}.pdf`"
							></wtm-md-editor>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="20">
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item ref="SelectedArticleAttachmentsIds_FormItem" prop="SelectedArticleAttachmentsIds">
							<template #label>
								<WtmLabelTooltip label="文章附件" tooltip="文章附件" />
							</template>
							<wtm-upload-file v-model="stateData.vmModel.SelectedArticleAttachmentsIds" :multi="true" clearable></wtm-upload-file>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item ref="Entity_CoverImageId_FormItem" prop="Entity.CoverImageId">
							<template #label>
								<WtmLabelTooltip label="封面图片" tooltip="文章封面图片" />
							</template>
							<wtm-upload-image v-model="stateData.vmModel.Entity.CoverImageId" clearable class="width100"></wtm-upload-image>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item ref="Entity_SortOrder_FormItem" prop="Entity.SortOrder">
							<template #label>
								<WtmLabelTooltip label="排序" tooltip="文章显示排序，数值越小越靠前" />
							</template>
							<el-input-number v-model="stateData.vmModel.Entity.SortOrder" clearable class="width100"></el-input-number>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="20">
					<el-col :xs="24" :lg="24" class="mb20">
						<el-form-item ref="SelectedArticleTagMappingsIds_FormItem" prop="SelectedArticleTagMappingsIds" label="文章标签关联">
							<el-transfer
								v-model="stateData.vmModel.SelectedArticleTagMappingsIds"
								clearable
								:data="stateData.AllSysArticleTags"
								:props="{ key: 'Value', label: 'Text' }"
							></el-transfer>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</el-card>
	</div>
</template>

<!--suppress JSAnnotator -->
<script setup lang="ts" name="message._system.common.vm.add;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, computed, nextTick, ComponentInternalInstance } from 'vue';
import { SysArticleApi as api } from '/@/views/article/sysarticle/api';
import other from '/@/utils/other';
import { ISysArticleVm } from '/@/views/article/sysarticle/api/interface';
import { IViewModel } from '/@/types/common';

// 常量定义
const BUTTON_TEXTS = {
	SAVE: '保存',
	SUBMIT: '提交',
	CLOSE: '关闭',
} as const;
const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const hasSavedOnce = ref(false);
const stateData = reactive<IViewModel<ISysArticleVm>>({
	vmModel: {
		Entity: {
			Title: null,
			SubTitle: null,
			Summary: null,
			Content: null,
			Status: null,
			CategoryId: null,
			SortOrder: null,
			IsTop: false,
			IsRecommend: false,
			CoverImageId: null,
			ViewCount: 0,
			LikeCount: 0,
			CommentCount: 0,
			FavoriteCount: 0,
			ShareCount: 0,
			ArticleTagMappings: null,
			ArticleAttachments: null,
		},
		ActionName: null,
		IsMyApprove: null,
		SelectedArticleTagMappingsIds: [],
		SelectedArticleAttachmentsIds: [],
	},
	AllSysArticleCategorys: [],
	AllSysArticleTags: [],
});

// 公共的响应处理函数
const handleApiResponse = (response: any, isSubmit = false) => {
	// 根据操作类型显示不同的消息
	if (isSubmit) {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '提交成功');
	} else {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.savetip') || '保存成功');
	}
	emit('refresh');
	closeDialog();
	loading.value = false; // 重置loading状态
};

// 统一的错误处理函数
const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

// 公共的表单提交函数
const handleApiRequest = (apiCall: () => Promise<any>, beforeSubmit: () => void, isSubmit = false) => {
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			loading.value = true;
			beforeSubmit();
			apiCall()
				.then((response: any) => handleApiResponse(response, isSubmit))
				.catch(handleError);
		}
	});
};

// 取消
const onClose = () => {
	closeDialog();
};

// 保存
const onSubmit = () => {
	handleApiRequest(
		() => {
			// 创建一个深拷贝，确保新增时不发送无效的 ID 字段
			const submitData = JSON.parse(JSON.stringify(stateData.vmModel));
			if (!submitData.Entity.ID) {
				// 如果没有有效的 ID，删除该字段
				delete submitData.Entity.ID;
			}
			return api().add(submitData);
		},
		() => {},
		true
	);
};

// 加载选择列表数据
const loadData = async () => {
	await Promise.allSettled([
		other.getSelectList('/api/SysArticle/GetSysArticleCategories', [], false).then((x) => (stateData.AllSysArticleCategorys = x)),
		other.getSelectList('/api/SysArticle/GetSysArticleTags', [], false).then((x) => (stateData.AllSysArticleTags = x)),
	]);
};

// 初始化页面数据
const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
		hasSavedOnce.value = true;
	}
};
// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		// 并行加载选择列表数据
		await loadData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

// 设置对话框头部按钮
const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.SUBMIT,
			type: 'primary',
			onClick: onSubmit,
			visible: true, // 已保存过时显示保存按钮
		},

		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];
	emit('updateHeaderButtons', headerButtons);
};
</script>
